/*
		ServEngine framework library
		A library to fast develop JEE online applications
	
		Copyright 2008 José Ignacio de Córdoba Álvaro

		Licensed under the Apache License, Version 2.0 (the "License");
		you may not use this file except in compliance with the License.
		You may obtain a copy of the License at

				http://www.apache.org/licenses/LICENSE-2.0

		Unless required by applicable law or agreed to in writing, software
		distributed under the License is distributed on an "AS IS" BASIS,
		WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
		See the License for the specific language governing permissions and
		limitations under the License.
	
		Jose Ignacio de Cordoba Alvaro
		http://ignacio.decordoba.com
*/

package com.servengine.user;

import com.servengine.struts.AdminServiceAction;

import com.servengine.util.MailRelay;

import java.io.IOException;

import java.util.ArrayList;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.transaction.UserTransaction;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 * This struts action class groups role admin actions.
 * @see Role
 * @see RoleActionForm
 */
public class RoleAdminActions extends com.servengine.struts.ClientAction implements AdminServiceAction
{
	private static org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog( RoleAdminActions.class.getName() );

	public void initAction(javax.naming.Context context)
	{
		log.info(getClass().getName()+" initialized");
	}
	public ActionForward create(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException
	{
	  UserSessionSBean userSession=getUserSession(request);
		RoleActionForm role = (RoleActionForm)form;
		try
		{
			Role roledto = new Role(userSession.getPortal(),role.getName());
			BeanUtils.copyProperties(role,roledto);
		} catch (Throwable e)
		{
			log.error(e.getMessage(),e);
		  saveErrors(request,getErrorsFromException(e));
			return mapping.findForward("error");
		}
		return mapping.findForward("success");
	}
	public ActionForward store(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException
	{
		/*if (role.getId()==null || role.getId().length()==0)
		{
		  ActionErrors errors = new ActionErrors();
		  errors.add("error",new ActionMessage("idcantbeempty"));
		  saveErrors(request,errors);
		  return mapping.findForward("validationerror");
		}
	  if (role.getId().equals("admin")) // Security check to avoid an admin to loose access to its system
	    {
	      ActionErrors errors = new ActionErrors();
	      errors.add("error",new ActionMessage("cantmodifyadminrole"));
	      saveErrors(request,errors);
	      return mapping.findForward("validationerror");
	    }*/
		 UserTransaction ut = null;
		try // logintext
		{
		  ut = getUserTransaction();
		  UserSessionSBean userSession=getUserSession(request);
		  RoleActionForm roleForm = (RoleActionForm)form;
			Role role = null;
			if (roleForm.getId()==null)
			{
				role = usermanager.getRole(userSession.getPortalid(),roleForm.getName());
				if (role==null)
					role = new Role(userSession.getPortal(),roleForm.getName());
				else
					roleForm.setId(role.getId());
			} else
				role = usermanager.getRole(userSession.getPortalid(),roleForm.getId());
			if ((role.getName().equals("user") || role.getName().equals("admin")) && !role.getName().equals(roleForm.getName()))
				throw new IllegalArgumentException("error.cantChangeMainRoleName");
			BeanUtils.copyProperties(role,roleForm);
			usermanager.persist(role);
			portalmanager.updateRoleAdminServiceActions(role);//Actualiza las acciones de este role segun la propiedad Transient adminServices
		  portalmanager.updateRoleServiceActions(role);//Actualiza las acciones de este role segun la propiedad Transient services
		  roleForm.setId(role.getId());
			userSession.refresh(portalmanager.getPortal(userSession.getPortalid()));
		  ut.commit();
			return unspecified(mapping,form,request,response);
		} catch (Throwable e)
		{
		  try
		  {
		    ut.rollback();
		  } catch (Exception e2)
		  {
		    log.error(e.getMessage(),e2);
		  }
			log.error(e.getMessage(),e);
		  saveErrors(request,getErrorsFromException(e));
			return mapping.findForward("error");
		}
	}
	public ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException
	{
	  UserTransaction ut = null;
		try
		{
		  ut = getUserTransaction();
		  UserSessionSBean userSession=getUserSession(request);
		  RoleActionForm role = (RoleActionForm)form;
			Role roledto = role.getId()==null ? usermanager.getRole(userSession.getPortalid(),role.getName()):
				usermanager.getRole(userSession.getPortalid(),role.getId());
			BeanUtils.copyProperties(role,roledto);
			ArrayList<Role> allRoles = new ArrayList<Role>();
			for (Integer id: userSession.getPortal().getRoleIds())
				allRoles.add(usermanager.getRole(userSession.getPortalid(),id));
			request.setAttribute("allRoles",allRoles);//Necesario para que los roles tengan los valores Lazy. Si los cogemos del portal no los tienen.
			ut.commit();
		  return mapping.findForward("success");
		} catch (Throwable e)
		{
		  try
		  {
		    ut.rollback();
		  } catch (Exception e2)
		  {
		    log.error(e.getMessage(),e2);
		  }
			log.error(e.getMessage(),e);
		  saveErrors(request,getErrorsFromException(e));
			return mapping.findForward("error");
		}
	}
	/**
	 * @deprecated
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 * @throws ServletException
	 */
	public ActionForward remove(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		try
		{
		  UserSessionSBean userSession=getUserSession(request);
			if (request.getParameterValues("id") != null && request.getParameterValues("id").length > 0)
				for (String roleId: request.getParameterValues("id"))
				{
					usermanager.removeRole(userSession.getPortalid(), new Integer(roleId));
					logManager.log(userSession.getPortalid(),userSession.getUser().getId(),"user","RoleAdminActions","remove",roleId,request.getRemoteAddr());
				}
//		  userSession.refreshPortal();
		} catch (Throwable e)
		{
			log.error(e.getMessage(), e);
		  saveErrors(request,getErrorsFromException(e));
			return mapping.findForward("error");
		}
		return mapping.findForward("roles");
	}
	public ActionForward roles(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
	  return mapping.findForward("roles");
	}
	public ActionForward multiMail(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		UserTransaction ut = null;
		try
		{
			ut = getUserTransaction();
			UserSessionSBean userSession=getUserSession(request);
		  RoleActionForm roleForm = (RoleActionForm)form;
			Collection<User> users = usermanager.getRole(userSession.getPortalid(),roleForm.getId()).getUsers();
			MailRelay mailRelay = getMailRelay();
			String portalEmail = portalmanager.getEmail(userSession.getPortalid()).toString();
			for (User user: users)
				try
				{
					mailRelay.send(portalEmail,user.getEmail(),roleForm.getMessageSubject(),roleForm.getMessageTextBody(),roleForm.getMessageHtmlBody());
				} catch (Throwable e)
				{
					log.error(user.getUserid()+"@"+user.getPortalid()+": "+e.getMessage(),e);
				}
			ut.commit();
			return mapping.findForward("multiMail");
		} catch (Throwable e)
		{
			try
			{
				ut.rollback();
			} catch (Exception e2)
			{
				log.error(e.getMessage(),e2);
			}
			log.error(e.getMessage(), e);
			saveErrors(request,getErrorsFromException(e));
			return mapping.findForward("error");
		}
	}
}
